package jsen.tool.ddd.adapter.infrastructure.strict;

import com.google.common.collect.Sets;
import io.jsen.meta.diff.obj.MetaObject;
import io.jsen.meta.diff.obj.complex.MetaComplex;
import io.jsen.meta.diff.support.MetaChangeModifier;
import io.jsen.meta.diff.support.MetaModifier;

import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author jsen
 * @date 2021/10/11
 */
public class DiffHelp {
    static Set<String> getChangeFields(MetaObject<?, ?> metaObject) {
        int modifier = metaObject.getModifier();
        if (MetaChangeModifier.isNoChange(modifier)) {
            return Collections.emptySet();
        }
        if (MetaModifier.isComplex(modifier)) {
            // 复杂对象
            return getComplexChangeField(metaObject);
        }
        return Sets.newHashSet(getField(metaObject));
    }

    private static Set<String> getComplexChangeField(MetaObject<?, ?> metaObject) {
        int modifier = metaObject.getModifier();
        if (MetaModifier.isComplex(modifier)) {
            Collection<MetaObject<?, ?>> cF = ((MetaComplex) metaObject).getVal().values();
            return cF.stream().filter(i -> MetaChangeModifier.isChange(i.getModifier())).map(DiffHelp::getField)
                    .collect(Collectors.toSet());
        }
        return null;
    }

    private static String getField(MetaObject<?, ?> metaObject) {
        return metaObject.getMetaRelation().getMetaField().getFieldDefine().toString();
    }
}
